import React, { memo, useEffect, useState } from "react";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { Button, Form, Input, Modal, Table, Space, message, TreeSelect } from "antd";
import { ResultEnum } from "@/enums/httpEnum";
import { getAllPermissionList, createPermission, updatePermission, deletePermission } from "@/api/modules/permission";
import { IPermission } from "@/api/interface/permission";
import { convertTreeSelectData, TreeNode } from "@/utils/util";
import useAuthPermission from "@/hooks/useAuthPermission";
import "./index.less";

// eslint-disable-next-line react/display-name
const PermissionManage = memo(() => {
	const [permissionList, setPermissionList] = useState<IPermission[]>([]);

	// 新建框
	const [isModalOpen, setIsModalOpen] = useState(false);
	const [form] = Form.useForm();
	const [submitting, setSubmitting] = useState(false);
	const [editId, setEditId] = useState<number | null>(null);
	const onFinish = () => {
		form.resetFields();
	};
	const createModal = () => {
		form.resetFields();
		setIsModalOpen(true);
	};

	const handleOk = () => {
		setIsModalOpen(false);
	};

	const handleCancel = () => {
		setEditId(null);
		setIsModalOpen(false);
	};

	const editorForm = (formData: IPermission) => {
		form.setFieldsValue(formData);
		setEditId(formData.id);
		console.log(formData);
		setIsModalOpen(true);
	};

	const handleSubmit = async () => {
		try {
			await form.validateFields();
			setSubmitting(true);
			const values = await form.getFieldsValue();
			let submitFn: Function = createPermission;
			console.log(values);
			const params = {
				...values
			};
			console.log(editId);
			if (editId) {
				params.id = editId;
				submitFn = updatePermission;
			}

			const { code, msg } = await submitFn(params);
			if (code === 200) {
				await getPermissions();
				message.success(msg);
				handleCancel();
				form.resetFields();
			}

			setSubmitting(false);
		} catch (err) {
			setSubmitting(false);
			console.log(err);
		}
	};

	// 获取数据

	const getPermissions = async () => {
		const { code, data } = await getAllPermissionList();
		if (code === ResultEnum.SUCCESS) {
			setPermissionList(data || []);
		}
		console.log(permissionList);
		// setPermissionList(res);
	};

	useEffect(() => {
		getPermissions();
	}, []);

	const { confirm } = Modal;
	const showConfirm = (id: number) => {
		confirm({
			title: "提示",
			icon: <ExclamationCircleOutlined />,
			content: "确定删除当前权限？此操作将会删除当前权限与它的全部子权限！",
			async onOk() {
				const { code, msg } = await deletePermission(id);
				if (code === 200) {
					message.success(msg);
					await getPermissions();
				}
			},
			onCancel() {
				console.log("Cancel");
			}
		});
	};

	const columns: any[] = [
		{
			title: "权限名称",
			dataIndex: "name",
			key: "id",
			align: "center"
		},
		{
			title: "权限说明",
			dataIndex: "description",
			key: "description",
			align: "center"
		},
		{
			title: "授权标识",
			dataIndex: "resource",
			key: "resource",
			align: "center"
		},
		{
			title: "创建人",
			dataIndex: "creator",
			key: "creator",
			align: "center",
			render: (creator: string, record: IPermission) => {
				return (
					<div>
						{creator}
						{record.creatorName ? `(${record.creatorName})` : ""}
					</div>
				);
			}
		},
		{
			title: "创建时间",
			dataIndex: "createTime",
			key: "createTime",
			align: "center"
		},
		{
			title: "操作",
			dataIndex: "id",
			key: "id",
			render: (id: number, record: IPermission) => {
				return (
					<Space>
						{useAuthPermission("permission:update") && <a onClick={() => editorForm(record)}>编辑</a>}
						{useAuthPermission("permission:delete") && <a onClick={() => showConfirm(id)}>删除</a>}
					</Space>
				);
			},
			align: "center"
		}
	];
	return (
		<div className="card permission-manage-box">
			<div className="create">
				{useAuthPermission("permission:add") && (
					<Button type="primary" onClick={createModal}>
						添加权限
					</Button>
				)}
			</div>
			<Table
				bordered={true}
				dataSource={permissionList?.map(item => {
					return {
						...item,
						key: item.id
					};
				})}
				columns={columns}
				rowKey={record => record.id}
			/>
			<Modal
				title="新建权限"
				open={isModalOpen}
				onOk={handleOk}
				onCancel={handleCancel}
				footer={[
					<Button key="back" onClick={handleCancel}>
						取消
					</Button>,
					<Button key="submit" type="primary" loading={submitting} onClick={handleSubmit}>
						确定
					</Button>
				]}
			>
				<Form<IPermission> form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} layout="horizontal" onFinish={onFinish}>
					<Form.Item label="权限" name="name" rules={[{ required: true }]}>
						<Input />
					</Form.Item>
					<Form.Item label="权限描述" name="description" rules={[{ required: true }]}>
						<Input />
					</Form.Item>
					<Form.Item label="授权标识" name="resource" rules={[{ required: true }]}>
						<Input />
					</Form.Item>

					<Form.Item label="选择权限上级" name="parentId">
						<TreeSelect
							treeData={convertTreeSelectData<TreeNode<IPermission>>(permissionList, (item: IPermission) => {
								return {
									title: item.name,
									value: item.id
								};
							})}
						/>
					</Form.Item>
				</Form>
			</Modal>
		</div>
	);
});
export default PermissionManage;
